package com.lej.home.player

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.ViewGroup
import com.lej.core.base.statusHeight
import com.lej.core.dsl.*
import com.lej.home.R
import com.lej.player.Player
import com.lej.player.PlayerView
import com.lej.player.manager.CustomManager
import com.qmuiteam.qmui.kotlin.onClick
import com.qmuiteam.qmui.util.QMUIDisplayHelper
import com.qmuiteam.qmui.util.QMUIStatusBarHelper
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack

class PlayerActivity : Activity() {
    companion object {
        const val URL = "url"
        fun start(context: Context, url: String) {
            val intent = Intent(context, PlayerActivity::class.java)
            intent.putExtra(URL, url)
            context.startActivity(intent)
        }
    }

    private lateinit var player: PlayerView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        QMUIStatusBarHelper.translucent(this)
        QMUIStatusBarHelper.setStatusBarDarkMode(this)
        player = PlayerView(this)
        setContentView(player)
        Player.init()
        init(player)
    }

    private fun init(playerView: PlayerView) {
        (window.decorView as ViewGroup).apply {
            ImageView {
                layout_width = 36
                layout_height = 36
                src = R.drawable.video_small_close
                margin_top = 12
                margin_start = 12 + QMUIDisplayHelper.px2dp(this@PlayerActivity, statusHeight)
                onClick { finish() }
            }
        }

        val source = intent.getStringExtra(URL)
        setConfig(playerView)
        playerView.setUpLazy(source, true, null, null, "")
        playerView.startPlayLogic()
    }

    private fun setConfig(playerView: PlayerView) {
        playerView.isStartAfterPrepared = true
        playerView.setIsTouchWiget(false)
        playerView.isReleaseWhenLossAudio = false
        playerView.isNeedShowWifiTip = false
        playerView.isAutoFullWithSize = true
        playerView.isLooping = true

        playerView.setVideoAllCallBack(object : GSYSampleCallBack() {
            override fun onQuitFullscreen(url: String?, vararg objects: Any) {
                super.onQuitFullscreen(url, *objects)
            }

            override fun onEnterFullscreen(url: String?, vararg objects: Any) {
                super.onEnterFullscreen(url, *objects)
            }

            override fun onAutoComplete(url: String?, vararg objects: Any) {
                super.onAutoComplete(url, *objects)
            }
        })
    }

    override fun onPause() {
        super.onPause()
        player.onVideoPause()
    }

    override fun onResume() {
        super.onResume()
        player.onVideoResume()
    }

    override fun onDestroy() {
        super.onDestroy()
        CustomManager.clearAllVideo()
    }
}
